import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import axios from "axios";

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  noLoading?: boolean;
}

export type Any = any;

/**
 * @description 接口数据返回结果无data
 */
export interface Result {
  code: number;
  message: string;
}

/**
 * @description 接口数据返回结果有data
 */
export interface ResultData<T = Any> extends Result {
  data: T;
  total?: number;
  value: T;
}

const axiosConfig = {
  baseURL: "http://192.168.1.113:5002",
  timeout: 50000
};

class HttpService {
  private service: AxiosInstance;

  public constructor(axiosConfig: AxiosRequestConfig) {
    this.service = axios.create(axiosConfig);

    /**
     * @description 请求拦截器
     */
    this.service.interceptors.request.use((config: CustomAxiosRequestConfig) => {
      if (config.headers && typeof config.headers.set === "function") {
        config.headers.set("Authorization", "null");
      }
      return config;
    });

    /**
     * @description 响应拦截器
     */
    this.service.interceptors.response.use((response: AxiosResponse) => {
      const { data } = response;
      return data;
    });
  }

  get<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.get(url, config);
  }
  post<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.post(url, data, config);
  }
  put<T>(url: string, data?: object, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.put(url, data, config);
  }
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<ResultData<T>> {
    return this.service.delete(url, config);
  }
}

export default new HttpService(axiosConfig);
